import pygame

clock = pygame.time.Clock()
import random
from pygame import *
from pygame.locals import *


# 己方飞机类
class HeroPlane(pygame.sprite.Sprite):
    # 存放所有飞机子弹的组
    bullets = pygame.sprite.Group()

    def __init__(self, screen):
        # 这个精灵的初始化方法必须调用
        pygame.sprite.Sprite.__init__(self)
        self.player = pygame.image.load("feiji/hero.gif")
        new_width = 50
        new_height = 70
        self.player = pygame.transform.scale(self.player, (new_width, new_height))
        # 根据图片image获取矩阵对象
        self.rect = self.player.get_rect()
        self.rect.topleft = [Manager.bg_size[0] / 2 - 50, 600]
        self.v = 5  # 定义飞机的速度
        self.screen = screen  # 记录当前窗口的对象
        self.bullets = pygame.sprite.Group()
        self.last_shot_time = pygame.time.get_ticks()  # 上一次发射子弹的时间

    def key_control(self):
        # 监听键盘，控制方向
        key_pressed = pygame.key.get_pressed()
        if key_pressed[K_w] or key_pressed[K_UP]:
            self.rect.top -= self.v
        if key_pressed[K_s] or key_pressed[K_DOWN]:
            self.rect.bottom += self.v
        if key_pressed[K_a] or key_pressed[K_LEFT]:
            self.rect.left -= self.v
        if key_pressed[K_d] or key_pressed[K_RIGHT]:
            self.rect.right += self.v
        if self.rect.right > Manager.bg_size[0] - 20:
            self.rect.right = Manager.bg_size[0] - 20
        elif self.rect.left < 0:
            self.rect.left = 0
        elif self.rect.bottom > Manager.bg_size[1]:
            self.rect.bottom = Manager.bg_size[1]
        if key_pressed[K_SPACE]:
            current_time = pygame.time.get_ticks()
            if current_time - self.last_shot_time >= 300:  # 修改子弹发射间隔
                bullet = Bullet(self.screen, self.rect.left, self.rect.top)
                self.bullets.add(bullet)
                HeroPlane.bullets.add(bullet)
                self.last_shot_time = current_time

    def update(self):
        self.key_control()
        self.display()

    def display(self):
        self.screen.blit(self.player, self.rect)
        self.bullets.update()  # 更新子弹坐标
        self.bullets.draw(self.screen)  # 将所有子弹添加到屏幕

    @classmethod
    def clear_bullets(cls):
        cls.bullets.empty()  # 清空子弹


# 己方子弹类
class Bullet(pygame.sprite.Sprite):
    def __init__(self, screen, x, y):
        pygame.sprite.Sprite.__init__(self)  # 精灵的初始化
        self.image = pygame.image.load("feiji/bullet.png")
        # 根据图片image获取矩阵对象
        self.rect = self.image.get_rect()
        self.rect.topleft = [x + 25, y - 22]
        self.screen = screen
        self.v = 15

    def update(self):
        # 修改子弹坐标
        self.rect.top -= self.v
        if self.rect.top < -22:
            self.kill()  # 如果子弹超出屏幕，则销毁子弹


# 敌方飞机类
class EnemyPlane(pygame.sprite.Sprite):
    # 存放敌方所有飞机子弹的组
    enemy_bullets = pygame.sprite.Group()

    def __init__(self, screen):
        # 这个精灵的初始化方法必须调用
        pygame.sprite.Sprite.__init__(self)
        self.hero = pygame.image.load("feiji/enemy0.png")  # 敌方飞机
        # 根据图片image获取矩阵对象
        self.rect = self.hero.get_rect()
        x = random.randrange(1, Manager.bg_size[0], 50)
        self.rect.topleft = [x, 0]
        self.v = 1  # 定义飞机的速度
        self.screen = screen  # 记录当前窗口的对象
        self.bullets = pygame.sprite.Group()
        self.direction = 'right'

    def display(self):
        self.screen.blit(self.hero, self.rect)
        self.bullets.update()  # 更新子弹坐标
        self.bullets.draw(self.screen)  # 将所有子弹添加到屏幕

    def update(self):
        self.auto_move()
        self.auto_fire()
        self.display()

    def auto_move(self):
        if self.direction == 'right':
            self.rect.right += self.v
        elif self.direction == 'left':
            self.rect.right -= self.v
        if self.rect.right > Manager.bg_size[0] - 20:
            self.direction = 'left'
        elif self.rect.right < 0:
            self.direction = 'right'
        self.rect.bottom += self.v

    def auto_fire(self):
        random_num = random.randint(1, 30)
        if random_num == 2:
            bullet = EnemyBullet(self.screen, self.rect.left, self.rect.bottom)
            self.bullets.add(bullet)
            # 把子弹添加到类属性的子弹组里
            EnemyPlane.enemy_bullets.add(bullet)

    @classmethod
    def clear_bullets(cls):
        cls.enemy_bullets.empty()  # 清空子弹


# 敌方子弹类
class EnemyBullet(pygame.sprite.Sprite):
    def __init__(self, screen, x, y):
        pygame.sprite.Sprite.__init__(self)  # 精灵的初始化
        self.image = pygame.image.load("feiji/bullet1.png")
        # 根据图片image获取矩阵对象
        self.rect = self.image.get_rect()
        self.rect.topleft = [x + 50 / 2 - 10 / 2, y + 39]
        self.screen = screen
        self.v = 3

    def update(self):
        # 修改子弹坐标
        self.rect.top += self.v
        if self.rect.top > Manager.bg_size[1]:
            self.kill()  # 如果子弹超出屏幕，则销毁子弹


# 游戏音效类
class GameSound(object):
    def __init__(self):
        pygame.mixer.init()
        pygame.mixer.music.load('feiji/music.1.wav')
        pygame.mixer.music.set_volume(0.4)  # 声音大小
        self.__bomb = pygame.mixer.Sound("feiji/bomb.wav")

    def playBackgroundMusic(self):
        pygame.mixer.music.play(-1)  # 开始播放音乐

    def playBombSound(self):
        pygame.mixer.Sound.play(self.__bomb)


# 碰撞类
class Bomb(object):
    def __init__(self, screen, type):
        self.screen = screen
        if type == "enemy0":
            # 加载爆炸资源
            self.mImage = [pygame.image.load("./feiji/enemy0_down" + str(v) + ".png") for v in range(1, 5)]
        else:
            self.mImage = [pygame.image.load("./feiji/enemy0_down" + str(v) + ".png") for v in range(1, 5)]
        # 设置当前爆炸播放索引
        self.mIndex = 0
        # 爆炸设置
        self.mPos = [0, 0]
        # 是否可见
        self.mVisible = False

    def action(self, rect):
        # 触发爆炸方法draw
        # 爆炸的坐标
        self.mPos[0] = rect.left
        self.mPos[1] = rect.top
        # 打开爆炸的开关
        self.mVisible = True

    def draw(self):
        if not self.mVisible:
            return
        self.screen.blit(self.mImage[self.mIndex], (self.mPos[0], self.mPos[1]))
        self.mIndex += 1
        if self.mIndex >= len(self.mImage):
            self.mIndex = 0
            self.mVisible = False


# 地图类
class GameBackground(object):
    def __init__(self, screen):
        self.scree = screen
        self.mImage1 = pygame.image.load("feiji/background.png")
        self.mImage2 = pygame.image.load("feiji/background.png")
        # 辅助地图移动
        self.y1 = 0
        self.y2 = -Manager.bg_size[1]

    # 移动地图
    def move(self):
        self.y1 += 2
        self.y2 += 2
        if self.y1 >= Manager.bg_size[1]:
            self.y1 = 0
        if self.y2 >= 0:
            self.y2 = -Manager.bg_size[1]

    def draw(self):
        self.scree.blit(self.mImage1, (0, self.y1))
        self.scree.blit(self.mImage2, (0, self.y2))


class Manager(object):
    bg_size = (480, 600)
    create_enemy_id = 10  # 创建敌机定时器的id
    game_over_id = 11  # 游戏结束倒计时的id
    is_game_over = False  # 游戏是否结束
    over_time = 1  # 重开游戏的倒计时时长

    def __init__(self):
        pygame.init()
        # 创建窗口
        self.screen = pygame.display.set_mode(Manager.bg_size)
        pygame.display.set_caption("飞机大战")
        # 创建一个图片当作背景
        self.background = pygame.image.load("feiji/background.png")
        self.map = GameBackground(self.screen)
        # 初始化一个装玩家精灵的group
        self.players = pygame.sprite.Group()
        # 初始化一个装敌机精灵的group
        self.enemys = pygame.sprite.Group()
        # 初始化一个玩家爆炸的对象
        self.player_bomb = Bomb(self.screen, 'player')
        # 初始化一个敌机爆炸的对象
        self.enemy_bomb = Bomb(self.screen, 'enemy')
        # 初始化一个声音播放的对象
        self.sound = GameSound()

    def exit(self):
        print('退出')
        pygame.quit()
        exit()

    def show_over_text(self):
        # 游戏结束，倒计时后重新开始
        self.drawText('gameover%d' % Manager.over_time, 100, Manager.bg_size[1] / 2, textHeight=50,
                      fontColor=[255, 0, 0])

    def game_over_timer(self):
        self.show_over_text()
        Manager.over_time -= 1
        if Manager.over_time == 0:
            # 参数2改为0，定时停止
            pygame.time.set_timer(Manager.game_over_id, 0)
            # 倒计时后重新开始
            Manager.over_time = 3
            Manager.is_game_over = False
            self.start_game()

    def start_game(self):
        # 重新开始游戏，有些类属性要清空
        EnemyPlane.clear_bullets()
        HeroPlane.clear_bullets()
        manager = Manager
        manager.main(self)

    def new_player(self):
        # 创建飞机对象 添加到玩家的组
        player = HeroPlane(self.screen)
        self.players.add(player)

    def new_enemy(self):
        # 创建敌机的对象 添加到敌机的组
        enemy = EnemyPlane(self.screen)
        self.enemys.add(enemy)

    def drawText(self, text, x, y, textHeight=30, fontColor=(255, 0, 0), backgroudColor=None):
        font_obj = pygame.font.Font('feiji/Abg.TTF', textHeight)
        # 配置要显示的文字
        text_obj = font_obj.render(text, True, fontColor, backgroudColor)
        # 获取要显示的对象的rect
        text_rect = text_obj.get_rect()
        # 设置显示对象的坐标
        text_rect.topleft = (x, y)
        # 绘制文字到指定区域
        self.screen.blit(text_obj, text_rect)

    def main(self):
        # 播放背景音乐
        self.sound.playBackgroundMusic()
        # 创建一个玩家
        self.new_player()
        # 开启创建敌机的定时器
        pygame.time.set_timer(Manager.create_enemy_id, 3000)
        while True:
            # 将背景图片放到窗口中
            self.screen.blit(self.background, (0, 0))
            self.map.move()
            self.map.draw()
            # 绘制文字
            self.drawText('secore:0', 0, 0)
            if Manager.is_game_over:
                # 判断游戏结束时才显示结束文字
                self.show_over_text()
            # 获取事件
            for event in pygame.event.get():
                # 判断事件
                if event.type == pygame.QUIT:
                    self.exit()
                elif event.type == Manager.create_enemy_id:
                    self.new_enemy()  # 创建新敌机
                elif event.type == Manager.game_over_id:
                    self.game_over_timer()

            # 调用爆炸的对象
            self.player_bomb.draw()
            self.enemy_bomb.draw()
            # 玩家飞机和和敌机子弹的碰撞判断
            if self.players.sprites():
                isover = pygame.sprite.spritecollide(self.players.sprites()[0], EnemyPlane.enemy_bullets, True)
                if isover:
                    Manager.is_game_over = True  # 标志着游戏结束
                    pygame.time.set_timer(Manager.game_over_id, 1000)  # 开始游戏倒计时
                    print("中弹")
                    self.player_bomb.action(self.players.sprites()[0].rect)
                    # 把玩家从精灵组移除
                    self.players.remove(self.players.sprites()[0])
                    # 爆炸的声音
                    self.sound.playBombSound()
            # 爆炸判断
            iscollide = pygame.sprite.groupcollide(self.players, self.enemys, True, True)
            if iscollide:
                Manager.is_game_over = True  # 标志着游戏结束
                pygame.time.set_timer(Manager.game_over_id, 1000)
                items = list(iscollide.items())[0]
                print(items)
                x = items[0]
                y = items[1][0]
                # 玩家爆炸图片
                self.player_bomb.action(x.rect)
                # 敌机爆炸图片
                self.enemy_bomb.action(y.rect)
                # 爆炸的声音
                self.sound.playBombSound()
            # 玩家子弹和所有敌机的碰撞判断
            is_enemy = pygame.sprite.groupcollide(HeroPlane.bullets, self.enemys, True, True)
            if is_enemy:
                items = list(is_enemy.items())[0]
                y = items[1][0]
                self.enemy_bomb.action(y.rect)
                self.sound.playBombSound()
            # 玩家子弹和敌机的碰撞判断
            is_enemy = pygame.sprite.groupcollide(HeroPlane.bullets, EnemyPlane.enemy_bullets, True, True)
            if is_enemy:
                for bullet in is_enemy.keys():
                    self.enemy_bomb.action(bullet.rect)
                self.sound.playBombSound()
            # 玩家飞机和子弹的显示
            self.players.update()
            # 敌机飞机和子弹的显示
            self.enemys.update()
            # 刷新窗口内容
            pygame.display.update()
            clock.tick(60)  # 每秒最多循环60次


if __name__ == '__main__':
    manager = Manager()
    manager.main()
